<template>
  <px-dialog v-model="dialogVisible" class="equip-dialog" :title="typeTitle" width="600px" @open="openDialog" @close="closeDialog">
    <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
      <px-form-item label="故障类型" prop="faultTypeName">
        <px-input v-model="formValue.faultTypeName" placeholder="请输入故障类型" maxlength="30" clearable show-word-limit />
      </px-form-item>
      <!-- <px-form-item label="故障统计日期" prop="statTime">
        <px-date-picker
          v-model="formValue.statTime"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeDate"
        />
      </px-form-item> -->
      <px-form-item v-if="props.dialogType === 'edit'" label="故障维修案例" prop="workOrderId">
        <px-select
          v-model="formValue.workOrderId"
          placeholder="请选择故障维修案例"
          clearable
          filterable
          multiple
          @focus="queryTable"
          @change="workOrderCodeChange"
        >
          <px-option v-for="item in workOrderCodeList" :key="item.id" :label="item.workOrderName" :value="item.id" />
        </px-select>
      </px-form-item>
    </px-form>
    <div class="equip-dialog-footer">
      <px-button @click="closeDialog">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </px-dialog>
</template>
<script setup lang="ts">
import { addFaultManage, editFaultManage, getByFaultType } from "@/api/erc/learn";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs } from "vue";
import { debounce } from "@pureadmin/utils";

// 调用父级-关闭弹窗、查询列表方法
const emits = defineEmits(["closeDialog", "queryTable"]);
// 父级传过来的值
const props = defineProps(["dialogVisible", "dialogType", "dialogRow", "eqpCode"]);
const dialogVisible = computed(() => props.dialogVisible);

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  typeTitle: "新增故障经验",
  formValue: {
    id: "",
    faultTypeName: ""
    // statTime: ""
  },
  workOrderCodeList: []
});
const { formValue, typeTitle, workOrderCodeList } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  faultTypeName: [{ required: true, message: "故障类型不能为空", trigger: "blur" }]
  // statTime: [{ required: true, message: "故障统计日期不能为空", trigger: "change" }]
}));

// 查询列表
const queryTable = async () => {
  const params = {
    pageNum: 1,
    pageSize: 9999,
    faultTypeCode: props.dialogRow.faultTypeCode
    // startTime: formValue.value.startTime || props.dialogRow.startTime,
    // endTime: formValue.value.endTime || props.dialogRow.endTime
  };
  const data = await getByFaultType(params);
  workOrderCodeList.value = data?.data;
};
// 获取开始日期及结束日期
const changeDate = val => {
  formValue.value.startTime = val[0];
  formValue.value.endTime = val[1];
};
const workOrderCodeChange = val => {
  const arr = workOrderCodeList.value.filter(item => {
    return item.workOrderCode === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.workOrderId = arr[0].id;
  }
};
// 打开弹窗
const openDialog = async () => {
  formRef.value.resetFields();
  if (props.dialogType === "add") {
    typeTitle.value = "新增故障经验";
    delete formValue.value.id;
  } else if (props.dialogType === "edit") {
    typeTitle.value = "编辑故障经验";
    const data = JSON.parse(JSON.stringify(props.dialogRow));
    const { id, faultTypeName, faultTypeCode, workOrders } = data;
    formValue.value.id = id;
    formValue.value.faultTypeName = faultTypeName;
    formValue.value.faultTypeCode = faultTypeCode;
    formValue.value.workOrderId = workOrders.map(item => item.workOrderId);
    queryTable();
  }
};
// 关闭弹窗
const closeDialog = () => {
  formValue.value = {};
  emits("closeDialog");
};
// 提交
const handleSubmit = debounce((formEl: any) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      const params = formValue.value;
      params.eqpCode = props.eqpCode;
      if (formValue.value.workOrderCode?.length > 20) {
        PxMessage.warning("最多选择20个案例");
        return;
      }
      if (props.dialogType === "add") {
        await addFaultManage(params);
        PxMessage.success("新增成功，请筛选“工单完成时间：全部”查看");
        emits("closeDialog");
        emits("queryTable");
      } else if (props.dialogType === "edit") {
        const workOrders = workOrderCodeList.value.filter(item => params.workOrderId.includes(item.id));
        params.workOrders = workOrders;
        await editFaultManage(params);
        PxMessage.success("编辑成功，请筛选“工单完成时间：全部”查看");
        emits("closeDialog");
        emits("queryTable");
      }
    }
  });
}, 200);
</script>
<style lang="scss" scoped>
.equip-dialog {
  .equip-dialog-footer {
    margin-top: 80px;
    text-align: right;
  }
}

:deep(.px-input) {
  width: 100%;
}

:deep(.px-select) {
  width: 100%;
}
</style>
